import { Component, Input, OnInit } from '@angular/core';
import { NzDrawerRef } from 'ng-zorro-antd/drawer';
import { NzMessageService } from 'ng-zorro-antd/message';
import { switchMap } from 'rxjs/operators';
import { FeatureDto, FeaturesService, GetFeatureListResultDto } from '../proxy';

enum ValueTypes {
  ToggleStringValueType = 'ToggleStringValueType',
  FreeTextStringValueType = 'FreeTextStringValueType',
  SelectionStringValueType = 'SelectionStringValueType',
}

@Component({
  selector: 'app-ref-feature',
  templateUrl: './ref-feature.component.html',
  styleUrls: ['./ref-feature.component.less'],
})
export class RefFeatureComponent implements OnInit {
  @Input() providerName: string;
  @Input() providerKey: string;

  valueTypes = ValueTypes;
  featureList: GetFeatureListResultDto;
  features: FeatureDto[] = [];

  constructor(
    private featuresService: FeaturesService,
    private drawerRef: NzDrawerRef<void>,
    private message: NzMessageService
  ) {}

  ngOnInit(): void {
    this.featuresService
      .get(this.providerName, this.providerKey)
      .subscribe(result => this.bindFeatureList(result));
  }

  bindFeatureList(featureList: GetFeatureListResultDto) {
    this.featureList = featureList;
    this.features = [];
    for (let group of this.featureList.groups) {
      for (let feature of group.features) {
        this.features = [
          ...this.features,
          {
            ...feature,
          },
        ];
      }
    }
  }

  getChangedFeatures(): FeatureDto[] {
    let result: FeatureDto[] = [];
    if (!this.featureList?.groups) return result;

    for (let group of this.featureList.groups) {
      for (let feature of group.features) {
        let oldFeature = this.features.find(x => x.name == feature.name);
        if (!oldFeature) continue;

        if (oldFeature.value != feature.value.toString()) {
          result = [...result, { ...feature, value: feature.value.toString() }];
        }
      }
    }
    return result;
  }

  close() {
    this.drawerRef.close();
  }

  save() {
    this.featuresService
      .update(this.providerName, this.providerKey, {
        features: this.getChangedFeatures(),
      })

      .pipe(switchMap(() => this.featuresService.get(this.providerName, this.providerKey)))
      .subscribe(result => {
        this.bindFeatureList(result);
        this.message.success('更新成功！');
      });
  }
}
